<?php

namespace App\Http\Controllers\Entity\Column;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Column\AlbumRequest;
use App\Jobs\Publish\AlbumJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Album;
use App\Models\Entity\Column\AlbumVasseti;
use App\Models\Entity\Column\Column;
use App\Models\Task\Task;
use App\Repositories\Entity\Column\AlbumRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;
use App\Classes\Publish\Publication;

class AlbumController extends Controller
{
    use ModelForm;

    /** @var  AlbumRepository */
    private $albumRepository;

    public function __construct(AlbumRepository $albumRepo)
    {
        $this->albumRepository = $albumRepo;
    }

    /**
     * Display a listing of the Album.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.column.albums.index_header'));
            $content->description(__('entity.column.albums.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new Album.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.albums.create_header'));
            $content->description(__('entity.column.albums.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Album in storage.
     *
     * @param AlbumRequest $request
     *
     * @return Response
     */
    public function store(AlbumRequest $request)
    {
        $input = $request->all();

        $image = $request->file('backimg'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.album');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['backimg'] = $rootDir . $fullPath;

                $input['backimg'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $album = $this->albumRepository->create($input);

        if ($album) {
            // 手动添加-添加-中间表
            if (is_array($request->get('cols'))) {
                $album->cols()->sync(array_filter($request->get('cols')));
            }
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // if (is_array($request->get('vassetis'))) {
            //     $album->vassetis()->sync(array_filter($request->get('vassetis')));
            // }
        }
        Flash::success(__('entity.column.albums.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.albums.index'));

    }

    /**
     * Display the specified Album.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $album = $this->albumRepository->findWithoutFail($id);

        if (empty($album)) {
            Flash::error(__('entity.column.albums.not_found'));

            return redirect(route('entity.column.albums.index'));
        }

        return view('entity.column.albums.show')->with('album', $album);

    }

    /**
     * Show the form for editing the specified Album.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.column.albums.edit_header'));
            $content->description(__('entity.column.albums.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Album in storage.
     *
     * @param  int $id
     * @param AlbumRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $input = $request->all();
        $album = $this->albumRepository->findWithoutFail($id);

        if (empty($album)) {
            Flash::error(__('entity.column.albums.not_found'));

            return redirect(route('entity.column.albums.index'));
        }
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $album->backimg;
            $uploadConfig = config('custom.base.upload.album');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                // $album->backimg = null;
                // $album->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        $sValidators = [
            // 'collist_no' => 'required|max:100|unique:collists,collist_no,' . $id,
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'subtitle'   => 'max:100',
            'short_desc' => 'max:100',
            // 'img'        => 'max:200',
        ];

        $validators = [];

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Album::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
                'name'       => '名称',
                'title'      => '标题',
                'subtitle'   => '副标题',
                'short_desc' => '描述',
            ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $image = $request->file('backimg'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径

                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;

                // 上传图片
                $uploadConfig = config('custom.base.upload.album');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['backimg'] = $rootDir . $fullPath;

                $input['backimg'] = $fullPath;

                // 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($album->backimg);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $album = $this->albumRepository->update($input, $id);

        if ($album) {
            // 手动添加-添加-中间表
            if (is_array($request->get('cols'))) {
                $album->cols()->sync(array_filter($request->get('cols')));
            }
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // if (is_array($request->get('vassetis'))) {
            //     $album->vassetis()->sync(array_filter($request->get('vassetis')));
            // }
        }
        Flash::success(__('entity.column.albums.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.albums.index'));
    }

    /**
     * Remove the specified Album from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $album = Album::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->first();
            if (empty($album)) {
                return response()->json(['message' => '只有状态为下线且已下线发布的才可以删除', 'status' => false]);
            }
        }
        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Album::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->pluck('id')->toArray();
            if ($flag = $this->albumRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.column.albums.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $album = $this->albumRepository->findWithoutFail($id);

        if (empty($album)) {
            Flash::error(__('entity.column.albums.not_found'));

            return redirect(route('entity.column.albums.index'));
        }

        // 2017/08/22 modify
        // $imgUrl       = $album->backimg;
        // $uploadConfig = config('custom.base.upload.album');
        // $driver       = $uploadConfig['driver'];
        // $dir          = $uploadConfig['dir'];

        // 根据配置得到根路径
        // $rootDir = config('filesystems.disks.' . $driver . '.upload');

        // $rootDir  = config('filesystems.disks.'.$driver.'.root');
        // $imgUrl = strchr($imgUrl, $rootDir);

        if ($flag = $this->albumRepository->delete($id)) {

            // 2017/08/22 modify
            // $bool = Storage::disk($driver)->delete($imgUrl);

            $album->cols()->detach();

            $album->vassetis()->detach();

            return response()->json(['message' => __('entity.column.albums.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [editAsset 编辑媒资界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editAsset($id)
    {
        $album = $this->albumRepository->findWithoutFail($id);

        if (empty($album)) {
            Flash::error(__('entity.column.albums.not_found'));

            return redirect(route('entity.column.albums.index'));
        }

        // 只能手动调用下函数
        Admin::script('entityColumnAlbumAsset();');
        // 分类
        $vcats = Vcat::get(['name', 'id']);
        // 归类数据
        $vcattags = Vcattag::get(['name', 'id']);

        return view('entity.column.album.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'album_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selected(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 专题id
            $album_id = $request->input('album_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = AlbumVasseti::whereHas('album', function ($query) use ($album_id) {
                if (!empty($album_id)) {
                    $query = $query->where('id', '=', $album_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = AlbumVasseti::with(['album', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('album', function ($query) use ($album_id) {
                    if (!empty($album_id)) {
                        $query = $query->where('id', '=', $album_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })->count();

            $data['data'] = AlbumVasseti::with(['album', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('album', function ($query) use ($album_id) {
                    if (!empty($album_id)) {
                        $query = $query->where('id', '=', $album_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function data(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 专题id
            $album_id = $request->input('album_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
            where(function ($query) use ($album_id) {
                if (!empty($album_id)) {
                    $query = $query->whereNotIn('id', AlbumVasseti::where(['album_id' => $album_id])->pluck('vasseti_id')->toArray());
                }
            })
                ->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }

            $data['recordsFiltered'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($search_value, $album_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($album_id)) {
                        $query = $query->whereNotIn('id', AlbumVasseti::where(['album_id' => $album_id])->pluck('vasseti_id')->toArray());
                    }
                })->count();

            $data['data'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($search_value, $album_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($album_id)) {
                        $query = $query->whereNotIn('id', AlbumVasseti::where(['album_id' => $album_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param [type] $album_id   [description]
     * @param [type] $vasseti_id [description]
     */
    public function addVasseti(Request $request)
    {
        $album_id   = $request->input('album_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果专题已经上线且发布,则不让新增、删除操作
        $data = Album::where('id', '=', $album_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该专题已上线发布,不能添加媒资!', 'status' => false]); // 该专题已上线发布,不能添加媒资
        }

        if (empty($album_id)) {
            return response()->json(['content' => '专题为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = AlbumVasseti::where(['album_id' => $album_id, 'vasseti_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $albumVasseti             = new AlbumVasseti();
                    $albumVasseti->album_id   = $album_id;
                    $albumVasseti->vasseti_id = $value;
                    if (!$albumVasseti->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = AlbumVasseti::where(['album_id' => $album_id, 'vasseti_id' => $vasseti_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $albumVasseti             = new AlbumVasseti();
            $albumVasseti->album_id   = $album_id;
            $albumVasseti->vasseti_id = $vasseti_id;
            $flag                     = $albumVasseti->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  [type] $album_id   [description]
     * @param  [type] $vasseti_id [description]
     * @return [type]             [description]
     */
    public function deleteVasseti(Request $request)
    {
        $album_id   = $request->input('album_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果专题已经上线且发布,则不让新增、删除操作
        $data = Album::where('id', '=', $album_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该专题已上线发布,不能删除媒资', 'status' => false]); // 该专题已上线发布,不能删除媒资
        }

        if (empty($album_id)) {
            return response()->json(['content' => '专题为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = AlbumVasseti::where(['album_id' => $album_id, 'vasseti_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = AlbumVasseti::where(['album_id' => $album_id, 'vasseti_id' => $vasseti_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Album::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $columns = Column::pluck('name', 'id');
            // $form->multipleSelect('cols', '栏目')->options($columns);
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // $vassetis = Vasseti::pluck('name', 'id');
            // $form->multipleSelect('vassetis', '媒资')->options($vassetis);
            $form->text('short_desc', '简介');
            $form->textarea('long_desc', '详述');
            $form->image('backimg', '背景图')->help('必填')->removable();
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Album::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 状态过滤
            Publication::statusFilter($request->input('status'), $request->input('published'), $grid);

            // //添加按钮
            // if (!\Gate::check('entity.column.albums.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.column.albums.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.column.albums.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.column.albums.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.column.albums.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 表格中的按钮, 新增专题详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                // 编辑媒资
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.albums.edit_asset')) {
                if (Admin::user()->can('entity.column.albums.edit_asset')) {
                    $url = route('entity.column.albums.edit_asset', ['albums' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="编辑媒资"><i class="fa fa-list"></i></a>');
                }
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.albums.up')) {
                    $url      = route('entity.column.albums.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('entity.column.albums.down')) {
                    $url      = route('entity.column.albums.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 上线发布按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('entity.column.albums.publish_one')) {
                    $url      = route('entity.column.albums.publish_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('entity.column.albums.publish_down_one')) {
                    $url      = route('entity.column.albums.publish_down_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('entity.column.albums.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.column.albums.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑,删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            // 添加按钮
            if (Admin::user()->cannot('entity.column.albums.create')) {
                $grid->disableCreation();
            }

            // 导出按钮
            if (Admin::user()->cannot('entity.column.albums.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.column.albums.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.column.albums.publish_down')) {
                    $url      = route('entity.column.albums.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.column.albums.publish')) {
                    $url      = route('entity.column.albums.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.column.albums.all_down')) {
                    $url      = route('entity.column.albums.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.column.albums.all_up')) {
                    $url      = route('entity.column.albums.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                $tools->append(new \App\Admin\Extensions\Tools\Album\AlbumStatus());
                $tools->append(new \App\Admin\Extensions\Tools\Album\AlbumPublished());
                // 批量按钮
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.column.albums.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.column.albums.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Album\ReleaseAlbum('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.column.albums.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Album\ReleaseAlbum('down'));
                    }
                    // 批量上线发布按钮
                    if (Admin::user()->can('entity.column.albums.publish_one')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Album\ReleaseAlbum('publish'));
                    }
                    // 批量下线发布按钮
                    if (Admin::user()->can('entity.column.albums.publish_down_one')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Album\ReleaseAlbum('publishDown'));
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable()->editable();
            $grid->column('title', '标题')->sortable()->editable();
            $grid->column('subtitle', '副标题')->sortable()->editable();
            $grid->column('short_desc', '简介')->sortable();
            // $grid->cols('栏目')->pluck('name')->label();
            // 2017/08/23 tian modify 添加媒资为跳转编辑
            // $grid->vassetis('媒资')->pluck('name')->label();
            $grid->column('long_desc', '详述')->sortable();
            $uploadConfig = config('custom.base.upload.album');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('backimg', '背景图')->image($host);
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 编号
                // $filter->like('ablum_no', '编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.column.albums.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        $total_num = DB::table('albums as a')
            ->join('album_vassetis as b', 'a.id', '=', 'b.album_id')
            ->where(['online_status' => 0, 'publish_down_status' => 1])
            ->pluck('a.id')->unique()->count();
        $notices   = [];
        // 已经上线的ids
        $notices[] = [Album::where(['online_status' => 1])->pluck('id'), 'ID为以下的专题已经上线'];
        // 还未下线发布的ids
        $notices[] = [Album::where(['publish_down_status' => 0])->pluck('id'), 'ID为以下的专题还未下线发布'];
        // 没有媒资的ids
        $notices[] = [DB::table('albums as a')
            ->whereNotExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('album_vassetis as b')
                    ->whereRaw('a.id = b.album_id');
            })
            ->whereNull('deleted_at')
            ->pluck('a.id'),
            'ID为以下的专题下面没有媒资'
        ];
        // 拼装提示信息
        $oparation  = '专题上线';
        $totalNum   = Album::count();
        $successNum = $total_num;
        $failNum    = $totalNum - $successNum;
        $content    = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '专题上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new AlbumJob(['dispatch', 'up'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.column.albums.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Album(), ['online_status' => 1]);
        $result = Publication::getTotalNum(new Album(), [
            [['online_status' => 1], 'ID为以下专题还没上线'],
        ], '专题下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '专题下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new AlbumJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.column.albums.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Album(), ['online_status' => 1, 'publish_status' => 0]);
        $result = Publication::getTotalNum(new Album(), [
            [['online_status' => 1], 'ID为以下专题还未上线: '],
            [['publish_status' => 0], 'ID为以下专题已经上线发布: '],
        ], '专题发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '专题发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new AlbumJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.column.albums.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Album(), ['online_status' => 0, 'publish_down_status' => 0]);
        $result = Publication::getTotalNum(new Album(), [
            [['online_status' => 0], 'ID为以下专题还未下线: '],
            [['publish_down_status' => 0], 'ID为以下专题已经下线发布: '],
        ], '专题下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '专题下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new AlbumJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.column.albums.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $acceptIds = $request->ids;
                // 过滤有媒资的专题ids
                $ids = DB::table('albums as a')
                    ->join('album_vassetis as b', 'a.id', '=', 'b.album_id')
                    ->whereIn('a.id', $acceptIds)
                    ->where(['online_status' => 0, 'publish_down_status' => 1])
                    ->pluck('a.id')->unique();
                // 不满足条件的ids,和原因
                $notices = [];
                // 已经上线的ids
                $alreadyOnlineIds = Album::whereIn('id', $acceptIds)->where(['online_status' => 1])->whereIn('id', $request->ids)->pluck('id');
                if ($alreadyOnlineIds->first()) {
                    $notices[] = [$alreadyOnlineIds, 'ID为以下的专题已经上线'];
                }
                // 还未下线发布的ids
                $notPublishDownIds = Album::whereIn('id', $acceptIds)->where(['publish_down_status' => 0])->whereIn('id', $request->ids)->pluck('id');
                if ($notPublishDownIds->first()) {
                    $notices[] = [$notPublishDownIds, 'ID为以下的专题还未下线发布'];
                }
                // 没有媒资的ids
                $hasNoVassetiIds = DB::table('albums as a')
                    ->whereNotExists(function ($query) {
                        $query->select(DB::raw(1))
                            ->from('album_vassetis as b')
                            ->whereRaw('a.id = b.album_id');
                    })
                    ->whereIn('a.id', $request->ids)
                    ->pluck('a.id');
                if ($hasNoVassetiIds->first()) {
                    $notices[] = [$hasNoVassetiIds, 'ID为以下的专题下面没有媒资'];
                }
                // 拼装提示信息
                $oparation  = '专题上线';
                $totalNum   = count($acceptIds);
                $successNum = $ids->count();
                $failNum    = $totalNum - $successNum;
                $content    = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Album(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.column.albums.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Album(), $request->ids, ['online_status' => 1, 'publish_status' => 0]);
                $result = Publication::myfilter(new Album(), $request->ids, [
                    [['online_status' => 1], 'ID为以下专题还未上线: '],
                    [['publish_status' => 0], 'ID为以下专题已经上线发布: '],
                ], '专题发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '专题发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new AlbumJob(['publish'], $ids, $taskid));
                    $url = route('entity.column.albums.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $albums      = Album::with(['cols', 'vassetis'])->whereIn('id', $ids)->get();
                $album_datas = AlbumJob::makeAlbums($albums);
                $result1     = Publication::insertApi('albums', $album_datas);
                $result2     = Publication::updateMany(new Album(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                $content     = ($result1 && $result2) ? $content : '上线发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.column.albums.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Album(), $request->ids, ['online_status' => 1]);
                $result = Publication::myfilter(new Album(), $request->ids, [
                    [['online_status' => 1], 'ID为以下专题还没上线'],
                ], '专题下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Album(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.column.albums.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Album(), $request->ids, ['online_status' => 0, 'publish_down_status' => 0]);
                $result = Publication::myfilter(new Album(), $request->ids, [
                    [['online_status' => 0], 'ID为以下专题还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下专题已经下线发布: '],
                ], '专题下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $albumsCount = DB::connection('interface')->table('albums')->whereIn('album_id', $ids)->count();
                if ($albumsCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('albums', 'album_id', $ids);
                } else {
                    $result1 = true;
                }
                // 更新状态
                $result2 = Publication::updateMany(new Album(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? $content : '下线发布失败!']);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int)$request->input('taskid');
        return Publication::progress($taskid);
    }

}
